package com.chucang.shucang.pms.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.base.exception.FastException;
import com.chucang.shucang.common.base.page.PageData;
import com.chucang.shucang.common.base.utils.OpsUtil;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.security.annotation.Inner;
import com.chucang.shucang.common.security.utils.SecurityUtil;
import com.chucang.shucang.pms.entity.CollectionBaseEntity;
import com.chucang.shucang.pms.entity.CollectionSyntheticEntity;
import com.chucang.shucang.pms.feign.UserService;
import com.chucang.shucang.pms.feign.vo.UserCollectionHoldInfoVO;
import com.chucang.shucang.pms.service.CollectionBaseService;
import com.chucang.shucang.pms.service.CollectionSyntheticService;
import com.chucang.shucang.pms.vo.CollectionSyntheticDetailResVO;
import com.chucang.shucang.pms.vo.CollectionSyntheticPageResVO;
import com.chucang.shucang.pms.vo.CollectionSyntheticRulesVO;
import com.chucang.shucang.pms.vo.SyntheticCollectionDetailResVO;
import com.chucang.shucang.pms.vo.query.CollectionSyntheticQuery;
import com.github.yitter.idgen.YitIdHelper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 藏品合成表
 *
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-09-12
 */
@RestController
@RequestMapping("/collectionsynthetic")
@RequiredArgsConstructor
@Api(tags = "藏品合成表")
public class CollectionSyntheticController {

    private final CollectionSyntheticService collectionSyntheticService;
    private final UserService userService;

    private final CollectionBaseService collectionBaseService;

    /**
     * 藏品合成分页
     *
     * @param collectionSyntheticQuery csq
     * @return r
     */
    @PostMapping("/collectionSyntheticPage")
    public R<PageData<CollectionSyntheticPageResVO>> collectionSyntheticPage(@RequestBody CollectionSyntheticQuery collectionSyntheticQuery) {
        PageData<CollectionSyntheticPageResVO> pageData = collectionSyntheticService.collectionSyntheticPage(collectionSyntheticQuery);
        return R.ok(pageData);
    }

    /**
     * 合成藏品详情
     *
     * @param id 藏品id
     * @return r
     */
    @GetMapping("/collectionSyntheticDetail/{id}")
    public R<Map<Integer, List<CollectionSyntheticDetailResVO>>> collectionSyntheticDetail(@PathVariable Long id) {
        //合成所需藏品信息
        LambdaQueryWrapper<CollectionSyntheticEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CollectionSyntheticEntity::getCollectionId, id);
        List<CollectionSyntheticEntity> list = collectionSyntheticService.list(lambdaQueryWrapper);
        Set<Long> collectionSet = new HashSet<>(16);
        list.forEach(c -> collectionSet.add(c.getSyntheticId()));
        //用户拥有对应藏品的数量
        UserCollectionHoldInfoVO userCollectionHoldInfoVO = new UserCollectionHoldInfoVO();
        userCollectionHoldInfoVO.setUserId(SecurityUtil.getUser().getId());
        userCollectionHoldInfoVO.setCollectionIdSet(collectionSet);
        R<Map<Long, Integer>> collectionHoldInfos = userService.getUserCollectionHoldInfos(userCollectionHoldInfoVO, SecurityConstant.FROM_IN);
        Map<Long, Integer> integerMap = OpsUtil.of(collectionHoldInfos)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取用户藏品信息异常"))
                .getData()
                .get();
        //藏品封面图及藏品名返回
        LambdaQueryWrapper<CollectionBaseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CollectionBaseEntity::getId, collectionSet);
        List<CollectionBaseEntity> baseEntities = collectionBaseService.list(queryWrapper);
        Map<Long, String> pictureMap = new HashMap<>(16);
        Map<Long, String> nameMap = new HashMap<>(16);
        baseEntities.forEach(cc -> {
            pictureMap.put(cc.getId(), cc.getCoverPicture());
            nameMap.put(cc.getId(), cc.getDcName());
        });
        Map<Integer, List<CollectionSyntheticEntity>> listMap = list.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(CollectionSyntheticEntity::getRule));
        Map<Integer, List<CollectionSyntheticDetailResVO>> returnMap = new HashMap<>(16);
        listMap.forEach((k, v) -> {
            List<CollectionSyntheticDetailResVO> detailResVOS = v.stream().map(vc -> {
                CollectionSyntheticDetailResVO detailResVO = new CollectionSyntheticDetailResVO();
                detailResVO.setNeedNum(vc.getQuantity());
                detailResVO.setHoldNum(integerMap.get(vc.getSyntheticId()));
                detailResVO.setCoverPicture(pictureMap.get(vc.getSyntheticId()));
                detailResVO.setCollectionName(nameMap.get(vc.getSyntheticId()));
                return detailResVO;
            }).collect(Collectors.toList());
            returnMap.put(k, detailResVOS);
        });
        return R.ok(returnMap);
    }

    /**
     * 合成规则
     *
     * @param id   合成藏品id
     * @param rule 规则编号
     * @return r
     */
    @Inner
    @GetMapping("/getCollectionSyntheticRules/{id}/{rule}")
    public R<List<CollectionSyntheticEntity>> getCollectionSyntheticRules(@PathVariable Long id, @PathVariable Integer rule) {
        LambdaQueryWrapper<CollectionSyntheticEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CollectionSyntheticEntity::getCollectionId, id)
                .eq(CollectionSyntheticEntity::getRule, rule);
        List<CollectionSyntheticEntity> list = collectionSyntheticService.list(lambdaQueryWrapper);
        if (CollUtil.isEmpty(list)) {
            return R.failed();
        }
        return R.ok(list);
    }

    /**
     * 更新合成库存量
     *
     * @param id 藏品id
     * @return r
     */
    @Inner
    @GetMapping("/updateCollectionSyntheticSurplus/{id}")
    public R<String> updateCollectionSyntheticSurplus(@PathVariable Long id) {
        CollectionBaseEntity byId = collectionBaseService.getById(id);
        LambdaUpdateWrapper<CollectionBaseEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(CollectionBaseEntity::getId, id)
                .set(CollectionBaseEntity::getSurplus, byId.getSurplus() - 1);
        collectionBaseService.update(lambdaUpdateWrapper);
        return R.ok();
    }

    /**
     * 新增合成规则
     *
     * @param collectionSyntheticRulesVO srv
     * @return r
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/addSyntheticRules")
    public R<String> addSyntheticRules(@Valid @RequestBody CollectionSyntheticRulesVO collectionSyntheticRulesVO) {
        Long collectionId = collectionSyntheticRulesVO.getCollectionId();
        AtomicInteger ruleNum = new AtomicInteger(1);
        List<CollectionSyntheticEntity> syntheticList = new ArrayList<>(16);
        for (int i = 0; i < collectionSyntheticRulesVO.getRuleTotal(); i++) {
            collectionSyntheticRulesVO
                    .getRules()
                    .getRule()
                    .get("rule" + i)
                    .forEach(r -> {
                        CollectionSyntheticEntity collectionSyntheticEntity = new CollectionSyntheticEntity();
                        collectionSyntheticEntity.setCollectionId(collectionId);
                        collectionSyntheticEntity.setSyntheticId(r.getSyntheticId());
                        collectionSyntheticEntity.setQuantity(r.getNeedNum());
                        collectionSyntheticEntity.setRule(ruleNum.get());
                        collectionSyntheticEntity.setId(YitIdHelper.nextId());
                        syntheticList.add(collectionSyntheticEntity);
                    });
            ruleNum.incrementAndGet();
        }
        collectionSyntheticService.saveBatch(syntheticList);
        return R.ok();
    }

    /**
     * 获取合成藏品详情信息
     * @param id 合成藏品详情
     * @return
     */
    @GetMapping("/getSyntheticCollectionDetail/{id}")
    public R<SyntheticCollectionDetailResVO> getSyntheticCollectionDetail(@PathVariable Long id){
        SyntheticCollectionDetailResVO res = collectionSyntheticService.getSyntheticCollectionDetail(id);
        return R.ok(res);
    }
}